﻿using System.Collections.Generic;
using System.Globalization;
using System.Text;
using CML.Intercamber.Business.Dao;
using CML.Intercamber.Business.Helper;
using CML.Intercamber.Business.Model;
using CML.Intercamber.Service.TaskManager;

namespace CML.Intercamber.Service.Tasks.MessageNotification
{
    /// <summary>
    /// envoi d'emails messages non lus 
    /// </summary>
    class TaskMessageNotification : BaseSimpleTask
    {
        protected override bool JobTraitement()
        {
            List<MailMessagesDetail> userToNotify = MailMessagesDao.ListMessagesToNotify();

            long lastIdUser = -1;
            List<MailMessagesDetail> messagesForCurrentUser = new List<MailMessagesDetail>();
            foreach (var mailMessagesDetail in userToNotify)
            {
                if (mailMessagesDetail.IdUser != lastIdUser)
                {
                    SendNotificationMailForSingleUser(messagesForCurrentUser);
                    messagesForCurrentUser = new List<MailMessagesDetail>();
                    lastIdUser = mailMessagesDetail.IdUser;
                }
                messagesForCurrentUser.Add(mailMessagesDetail);
            }
            if (messagesForCurrentUser.Count > 0)
                SendNotificationMailForSingleUser(messagesForCurrentUser);

            return true;
        }


        protected void SendNotificationMailForSingleUser(List<MailMessagesDetail> mess)
        {
            if (mess.Count == 0)
                return;
            string mail = mess[0].Email;
            Logger.Info(FormatTaskLogMessage("Sending notification mail to " + mail));

            string userLanguage = mess[0].IdLanguage;
            var culture = new CultureInfo(userLanguage);

            string mailSubject = Resources.Intercamber.ResourceManager.GetString("Service_MessageNotificationSubject", culture);
            StringBuilder content = new StringBuilder();
            int nbNotifications = 0;
            foreach (var m in mess)
            {
                content.Append(
                    string.Format(Resources.Intercamber.ResourceManager.GetString("Service_MessageNotificationBodyItem", culture),
                    m.UnreadMessagesCount.ToString(), m.DestName + " (" + m.DestEstablishmentName + ") " + (m.DateLastMessage != null ? DateTimeHelper.FormatDate(m.DateLastMessage.Value, "dd/MM/yyyy HH:mm") : "")
                    ));
                content.Append("\r\n");
                nbNotifications ++; 
            }
            string mailBody = string.Format(Resources.Intercamber.ResourceManager.GetString("Service_MessageNotificationBody", culture), content.ToString());
            bool sent = MailHelper.SendMail(mail, string.Format(mailSubject, nbNotifications), mailBody);
        }
    }
}
